const Koa = require('koa')
const Router = require('koa-router')

//  实例化
const app = new Koa()
const router = new Router()

router.get('/', async (ctx) => {
  ctx.body = 'home'
})

router.get('/news', async (ctx) => {
  ctx.body = 'news'
})

// 假设前端的请求路径  http://localhost:3000/newsContent?aid=123&name=zs
router.get('/newsContent', async (ctx) => {

  // 推荐方式
  // 获取路由传递的参数
  console.log(ctx.query)
  // { aid: '123', name: 'zs' }

  console.log(ctx.querystring)
  // aid=123&name=zs

  // console.log(ctx.request)
  /**
   * {
          method: 'GET',
          url: '/newsContent?aid=123&name=zs',
          header: {
          host: 'localhost:3000',
              connection: 'keep-alive',
              'cache-control': 'max-age=0',
              'upgrade-insecure-requests': '1',
              'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
          (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
              'sec-fetch-user': '?1',
              accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,im
          age/apng,*;q=0.8,application/signed-exchange;v=b3;q=0.9',
              'sec-fetch-site': 'none',
              'sec-fetch-mode': 'navigate',
              'accept-encoding': 'gzip, deflate, br',
              'accept-language': 'en,zh;q=0.9,zh-CN;q=0.8'
          }
      }
   */

  console.log(ctx.request.url)
  // /newsContent?aid=123&name=zs

  console.log(ctx.request.query)
  //[Object: null prototype] { aid: '123', name: 'zs' }

  console.log(ctx.request.querystring)
  //aid=123&name=zs

  ctx.body = '新闻详情'
})

// http://localhost:3000/page/112
router.get('/page/:id', async (ctx) => {
  console.log(ctx.params)
  // {id: 112}
  ctx.body = '新闻详情'
})

// http://localhost:3000/pages/112/qwe
router.get('/pages/:id/:bid', async (ctx) => {
  console.log(ctx.params)
  // { id: '112', bid: 'qwe' }
  ctx.body = '新闻详情'
})

//启动路由
app.use(router.routes()).use(router.allowedMethods())
// 设置响应头

// 监听在3000端口
app.listen(3000)